import { plugin } from "alemon";
import data from '../../model/fantasyData.js';
import {
  __PATH,
  Add_HP,
  Read_player,
  existplayer,
  Read_equipment,
  Write_equipment,
  Write_player,
  Write_state,
  Read_bag,
  Write_bag,
  Read_mapevent,
  Judge_up,
  Add_bag,
  Read_skill,
  Read_state,
  Read_equiplist,
  Num_bag,
  Read_thingtype,
  my_equip,
} from '../../model/fantasy.js';
import { basename } from "path/win32";
import fs from 'fs';
import path from 'path';
import { AppName } from '../../app.config.js';


export class UserStart extends plugin {
  constructor() {
    super({
      priority: 200,
      rule: [
                {
                    reg: /^\/菜单$/,
                    fnc: 'list'
                },
                {
                    reg: /^注册.*$/,
                    fnc: 'zhuce'
                },{
                    reg: /^属性$/,
                    fnc: 'shuxing'
                },{
                    reg: /^信息$/,
                    fnc: 'xinxi'
                },{
                    reg: /^探索周边$/,
                    fnc: 'startTS'
                },{
                    reg: /^背包.*$/,
                    fnc: 'My_bag'
                },{
                    reg: /^地图信息$/,
                    fnc: 'Map_information'
                },{
                    reg: /^#本地备份$/,
                    fnc: 'copy'
                },{
                    reg: /^#本地恢复$/,
                    fnc: 'paste'
                },{
                    reg: /^技能信息.*$/,
                    fnc: 'skill_infor'
                },{
                    reg: /^装备.*$/,
                    fnc: 'equip'
                },{
                    reg: /^卸下.*$/,
                    fnc: 'unequip'
                },{
                    reg: /^我的装备$/,
                    fnc: 'myequip'
                },

      ],
    });
    
  }
    //你好
    async list(e){
    e.reply(`======菜单======\n[注册+昵称]进行穿越\n[信息]查看人物信息\n[属性]查看人物属性\n[探索周边]6分钟一次，进行地图探索\n[地图信息]查看当前地图信息\n[背包+物品类型]类型有装备、道具、材料、技能书，查看背包内该类型物品\n————————————\n【当前地图100%探索后】\n[上|下|左|右]3s一次，进行移动触发事件\n[战斗面板]查看战斗内操作指令\n[探索周边]6分钟一次，进行地图探索；不可和移动叠加\n[我的技能]查看已会技能\n[技能信息+技能名]查看该技能信息\n[设置技能1|2|3|4+技能名]设置技能指令\n[装备+装备名]穿戴该装备\n[卸下+装备名]卸下该装备\n[使用+物品名]战斗外使用物品`);
    return ;
    }


    //#注册
    async zhuce(e) {
        e.cmd_msg = e.cmd_msg.replace("/", "");
        //有无存档
        let usr_qq = e.user_id;
        let ifexistplay = await existplayer(e.user_id);
        if (ifexistplay) {
            e.reply("请不要重复注册哦~")
            return;
        }
        //初始化玩家信息
        let ran001 = 100 + Math.floor(800 * Math.random());
        let ran002 = 100 + Math.floor(800 * Math.random());
        let ran01 = Math.random();
        let ran02 = Math.random();
        let ran03 = Math.random();
        let ran04 = Math.random();
        let ran05 = Math.random();
        let ran06 = Math.random();
        let ran07 = ran01 + ran02 +ran03 + ran04 + ran05 + ran06;
        let ran1 = 1.5 * ran01 / ran07 + 0.5;
        let ran2 = 1.5 * ran02 / ran07 + 0.5;
        let ran3 = 1.5 * ran03 / ran07 + 0.5;
        let ran4 = 1.5 * ran04 / ran07 + 0.5;
        let ran5 = 1.5 * ran05 / ran07 + 0.5;
        let ran6 = 1.5 * ran06 / ran07 + 0.5;
        let talent = Math.floor(100 * Math.random())
        let name = e.cmd_msg.replace(/^注册/,'')
        if(name == "" || name == undefined){
        e.reply("请输入注册名称~")
        return;
        }
        let new_player = {
            "id": e.user_id,
            "sex": 0,//性别
            "昵称": name,
            "签名": "哎呀，还没有想好呢！",
            "等级": 0,
            "经验": 0,
            "位置": "幽静森林",
            "坐标x": ran001,
            "坐标y": ran002,
            "属性点":0,
            "天赋":talent,
            "体质潜力":ran1,
            "精神潜力":ran2,
            "力量潜力":ran3,
            "智力潜力":ran4,
            "敏捷潜力":ran5,
            "幸运潜力":ran6,
            "生命上限":0,
            "魔力上限":0,
            "当前生命":0,
            "当前魔力":0,
            "物攻":0,
            "魔攻":0,
            "物防":0,
            "魔防":0,
            "暴击":0,
            "暴伤":0,
            "命中":0,
            "闪避":0,
            "暴免":0,
            "暴抗":0,
            "韧性":0,
            "速度":0,
            "移速":0,
            "技能":[]

        }
        await Write_player(e.user_id, new_player);
        await Write_state(usr_qq, "探索")

        //初始化装备
        let new_equipment = {
            "武器": {"名称": ""},
            "副手": {"名称": ""},
            "头肩": {"名称": ""},
            "上装": {"名称": ""},
            "腰带": {"名称": ""},
            "下装": {"名称": ""},
            "鞋子": {"名称": ""},
            "戒指": {"名称": ""},
            "手镯": {"名称": ""},
            "项链": {"名称": ""}
        }
        await Write_equipment(e.user_id, new_equipment);
        //初始化背包
        let new_bag = {
            "铜币": 10000,
            "银币": 0,
            "金币": 0,
            "装备": [],
            "道具": [],
            "技能书": [],
            "材料": [],
           
        }
        let player = await Read_player(e.user_id);
        await Write_bag(e.user_id, new_bag);
        await Add_HP(e.user_id, player.生命上限);
        e.reply(`一阵眩目的白光将你笼罩，逼得你睁不开眼。\n再次睁开眼时，你发觉周围是一片茂密的森林。`)
        e.reply(`[${player.昵称}]穿越成功！\n————————————\n【不删档测试中———】\n发送[属性]查看角色属性\n发送[信息]查看角色信息\n发送[菜单]查看更多指令`)
        return;
    }
 
 
  //角色属性
  async shuxing(e) {
    e.cmd_msg = e.cmd_msg.replace("/", "");
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
      return;
    }
    if(await Read_state(usr_qq) == "组队战斗"){
      return;
    }
    let equ = await Read_equipment(usr_qq);
    await Write_equipment(usr_qq, equ);
    let player = await Read_player(usr_qq);
    let img = (`【${player.昵称} Lv.${player.等级}】\n————————————\n生命: ${player.当前生命}\/${player.生命上限}\n魔力: ${player.当前魔力}\/${player.魔力上限}\n物理攻击：${player.物攻}\n魔法攻击：${player.魔攻}\n物理防御：${player.物防}\n魔法防御：${player.魔防}\n命中：${player.命中}\n闪避：${player.闪避}\n暴击：${player.暴击}\n暴伤：${player.暴伤}\n暴免：${player.暴免}\n暴抗：${player.暴抗}\n韧性：${player.韧性}\n速度：${player.速度}`)
    e.reply(img);
    return;
  }


  async xinxi(e){
    e.cmd_msg = e.cmd_msg.replace("/", "");
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
      return;
    }
    if(await Read_state(usr_qq) == "组队战斗"){
      return;
    }
    let player = await Read_player(usr_qq);
    let dengji = player.等级;
    let level = data.level_list;
    let level_max = level[dengji].经验;
    let talent = data.talent_list;
    let talent_word = "";
    let len = talent.length;
    for(let i = 0; i < len; i++){
        if(player.天赋 >= talent[i].数)
            talent_word = talent[i].字;
    }
    let img = (`【${player.昵称}】\n————————————\n等级：${player.等级}\n经验：${player.经验}\/${level_max}\n天赋：${talent_word}\n位置：${player.位置}\n坐标：\( ? , ? \)\n属性点：${player.属性点}`);
    e.reply(img);
    return;
}


async startTS(e){
    e.cmd_msg = e.cmd_msg.replace("/", "");
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
      return;
    }
    if(await Read_state(usr_qq) == "组队战斗"){
      return;
    }
    let player = await Read_player(usr_qq);
    const nowTime = new Date().getTime() // 获取当前日期的时间戳
    const restTime = nowTime - player.探索记录

    if(restTime < 360000){
       let minute = Math.floor((360000 - restTime) / 60000);
       let second = Math.floor((360000 - restTime - 60000 * minute) / 1000 + 1)
    e.reply(`【${player.昵称}】\n————————————\n您还在休息中哦~\n距离整装待发还差${minute}分${second}秒`)
    return;
    }else{
      let progress = player["进度"];
      if (progress === undefined) {
        player["进度"] = [];
      }
      player.探索记录 = nowTime;

      //搜索进度
      let name = player.位置;
      let value = (player && player["进度"] && player["进度"][name]) || 0;
        if(value == 0){
          player["进度"] = {};
          player["进度"][name] = 1;
        }else if(value == 100){
          player["进度"][name] = 100;
        }else{
          player["进度"][name] += 1;
        }

      //匹配进度相应探索
     let event = await Read_mapevent(player.位置);
     let i = -1;
     let indexes = event
       .map((obj, index) => obj["进度"] === value ? index : false)
       .filter(index => index !== false);
       if(indexes == false){
       indexes = event
       .map((obj, index) => obj["进度"] === -1 ? index : false)
       .filter(index => index !== false);
       }
       if(indexes !== false){
       let len = Math.floor(Math.random() * indexes.length);
       i = indexes[len];
       }
     //读取相应数据
     let EXP = Math.floor(0.8 * event[i]["经验"] + 0.4 * event[i]["经验"] * Math.random());
     let msg1 = "";
     let msg2 = "";
     let msg0 = "";
     player.经验 += EXP;
     if(EXP > 0){
     msg1 = `\n★获得${EXP}经验★`
     }else if(EXP < 0){
     msg1 = `\n★损失${-EXP}经验★`
     }else{
     msg1 = "";
     }
     if(event[i].数量 > 0){
       await Add_bag(usr_qq, event[i].物品, event[i].数量)
     msg2 = `\n★获得[${event[i]["物品"]}] * ${event[i]["数量"]}★`
     }
     let event_word = event[i]["描述"];
     if(msg1 !== "" || msg2 !== "" ){
       msg0 = "\n————————————";
     }
     e.reply(`【${player.昵称}】\n${event_word}` + msg0 + msg1 + msg2);
       if(value == 99){
         await Write_state(usr_qq, "自由");
         setTimeout(function() {
                e.reply(`【${player.昵称}】\n————————————\n费尽千辛万苦，你终于将此片区域摸索了一番。\n你对这里有了一个大致的了解,稍微清楚了这里的方位。\nTips:发送[地图信息]查看地图详情`);
              }, 100);
       }
     await Write_player(usr_qq, player);
     setTimeout(async function() {
                await Judge_up(usr_qq, e);
              }, 100);
     return;
}

}


async My_bag(e){
    e.cmd_msg = e.cmd_msg.replace("/", "");
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
      return;
    }
    let player = await Read_player(usr_qq);
    let name0 = e.cmd_msg.replace(/^背包/,'');
    let name = name0.replace(/\d+/g, "");
    let match = name0.match(/\d+$/);
    let num = match ? match[0] : 1;
    const bag = await Read_bag(usr_qq);
    if((name == "装备")||(name == "材料")||(name == "道具")||(name == "技能书")){
      let len = bag[name].length;
      let len1 = Math.floor((len - 1)/ 10) + 1;
      let word = `【[${player.昵称}]的${name}背包】\n————————————`;
      if(len == 0){
        e.reply(`【[${player.昵称}]的${name}背包】\n————————————\n[空空如也]\n————————————\n【第1页，共1页】\nTips:发送[背包+类别+页码]查看背包`);
        return;
      }
      let word0 = "";
      let word1 = "";
      let i = 10 * (num - 1);
      let b = i + 10;
      if(num == len1){
        b = len;
      }
      for(i; i < b; i++){
      word0 = `[${bag[name][i]["名称"]}]`;
      word1 = `${bag[name][i]["数量"]}`;
      if(word1 == "" || word1 == undefined){
        word1 = 1;
      }
      if(word0 !== "" && word0 !== undefined){
        word = word + `\n ${word0} * ${word1}`;
      }
      }
      e.reply(word + `\n————————————\n【第${num}页，共${len1}页】\nTips:发送[背包+类别+页码]查看背包`)
    }else{
      e.reply(`查看类别不对哦~\n不存在类别[${name}]\nTips:发送[背包+类别+页码]查看背包`)
    }
}

  async Map_information(e){
    e.cmd_msg = e.cmd_msg.replace("/", "");
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
      return;
    }
    if(await Read_state(usr_qq) == "组队战斗"){
      return;
    }
    let player = await Read_player(usr_qq);
    let local = player["位置"];
    let jindu = (player && player["进度"] && player["进度"][local]) || 0;
    let jindu_word = "";
    if(jindu >= 0 && jindu < 100){
      const nowTime = new Date().getTime() // 获取当前日期的时间戳
      const restTime = nowTime - player.探索记录
      if(restTime <= 360000 && restTime >= 0){
       let minute = Math.floor((360000 - restTime) / 60000);
       let second = Math.floor((360000 - restTime - 60000 * minute) / 1000 + 1)
          jindu_word = `\n☆已探索：${jindu}%☆\n[距离下一次探索${minute}分${second}秒]`;
        }else{
          jindu_word = `\n☆已探索：${jindu}%☆\n[已经可以下一次探索了！]`;
        }
    }else if(jindu >= 100){
      jindu_word = `\n★探索已完成★`
    }else{
      const nowTime = new Date().getTime() // 获取当前日期的时间戳
      const restTime = nowTime - player.探索记录
      if(restTime <= 360000 && restTime >= 0){
       let minute = Math.floor((360000 - restTime) / 60000);
       let second = Math.floor((360000 - restTime - 60000 * minute) / 1000 + 1);
          jindu_word = `\n☆已探索：${jindu}%☆\n[距离下一次探索${minute}分${second}秒]`;
        }else{
          jindu_word = `\n☆已探索：${jindu}%☆\n[已经可以下一次探索了！]`;
        }
    }
    let img = `【${player.昵称} Lv.${player.等级}】\n————————————\n所在区域：[${local}]` + jindu_word;
    img = img + `\n————————————\n【???无法查阅更多信息???】`;
    e.reply(img);
    return;
    }  

    async copy(e){
    e.cmd_msg = e.cmd_msg.replace("#", "");
    function copyFolderSync(source, target) {
    if (!fs.existsSync(target)) {
      fs.mkdirSync(target);
    }
    fs.readdirSync(source).forEach((file) => {
      const sourcePath = path.join(source, file);
      const targetPath = path.join(target, file);

      if (fs.lstatSync(sourcePath).isDirectory()) {
        copyFolderSync(sourcePath, targetPath);
      } else {
        fs.copyFileSync(sourcePath, targetPath);
      }
    });
    }
    const __dirname = path.resolve() + path.sep + 'plugins' + path.sep + AppName;
    const data_path1 = path.join(__dirname, '/resources/data/player/');
    const data_path2 = path.join(__dirname, '/resources/data/equipment/');
    const data_path3 = path.join(__dirname, '/resources/data/bag/');
    const new_path0 = path.resolve();
    const new_path1 = path.join(new_path0, '/data备份/player/');
    const new_path2 = path.join(new_path0, '/data备份/equipment/');
    const new_path3 = path.join(new_path0, '/data备份/bag/');
    copyFolderSync(data_path1, new_path1);
    copyFolderSync(data_path2, new_path2);
    copyFolderSync(data_path3, new_path3);
    e.reply(`本地备份存档成功！`)
    }

    async paste(e){
    e.cmd_msg = e.cmd_msg.replace("#", "");
    function copyFolderSync(source, target) {
    if (!fs.existsSync(target)) {
      fs.mkdirSync(target);
    }
    fs.readdirSync(source).forEach((file) => {
      const sourcePath = path.join(source, file);
      const targetPath = path.join(target, file);

      if (fs.lstatSync(sourcePath).isDirectory()) {
        copyFolderSync(sourcePath, targetPath);
      } else {
        fs.copyFileSync(sourcePath, targetPath);
      }
    });
    }
    function deleteFolderRecursive(folderPath) {
    if (fs.existsSync(folderPath)) {
      fs.readdirSync(folderPath).forEach((file, index) => {
        const curPath = path.join(folderPath, file);
        if (fs.lstatSync(curPath).isDirectory()) {
          deleteFolderRecursive(curPath);
        } else {
          fs.unlinkSync(curPath);
        }
      });
      fs.rmdirSync(folderPath);
    }
    }
    const __dirname = path.resolve() + path.sep + 'plugins' + path.sep + AppName;
    const data_path1 = path.join(__dirname, '/resources/data/player/');
    const data_path2 = path.join(__dirname, '/resources/data/equipment/');
    const data_path3 = path.join(__dirname, '/resources/data/bag/');
    const backup_path0 = path.resolve();
    const backup_path1 = path.join(backup_path0, '/data备份/player/');
    const backup_path2 = path.join(backup_path0, '/data备份/equipment/');
    const backup_path3 = path.join(backup_path0, '/data备份/bag/');
    deleteFolderRecursive(data_path1);
    deleteFolderRecursive(data_path2);
    deleteFolderRecursive(data_path3);
    copyFolderSync(backup_path1, data_path1);
    copyFolderSync(backup_path2, data_path2);
    copyFolderSync(backup_path3, data_path3);
    e.reply(`本地恢复存档成功！`)
    }

    async skill_infor(e){
    e.cmd_msg = e.cmd_msg.replace("/", "");
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
      return;
    }
    let skill_name = e.cmd_msg.replace("技能信息","");
    let skill_list = await Read_skill(usr_qq);
    let skill = skill_list.find(obj => obj["名称"] == skill_name )
    const type = skill["类别"];
    const element = skill["属性"];
    const power = skill["倍率"];
    const mp = skill["魔耗"];
    const time = skill["冷却"];
    e.reply(`======技能信息======\n名称：${skill_name}\n类型：${type}\n属性：${element}\n威力：${power}(初窥门径)\n魔耗：${mp}\n冷却：${time}`);
    return;

    } 


    //#装备
    async equip(e) {
        e.cmd_msg = e.cmd_msg.replace("/", "");
        //有无存档
        let usr_qq = e.user_id;
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
          return;
        }
        if(await Read_state(usr_qq) == "组队战斗"){
          return;
        }
        const thing = e.cmd_msg.replace("装备", "");
        let number = await Num_bag(usr_qq, thing);
        let player = await Read_player(usr_qq);
        if(number == false){
          e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n[${thing}]不存在于这方世界`);
          return;
        }
        if(number < 1){
          e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n你没有该装备哦~\nTips:发送[背包装备]查看背包内装备`)
          return;
        }
        let player_equ = await Read_equipment(usr_qq);
        let equip_list = await Read_equiplist(usr_qq);
        let equip = equip_list.find(obj => obj["名称"] == thing);
        if(equip == undefined){
          e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n[${thing}]不存在于这方世界`);
          return;
        }
        const level = equip["等级"];
        if(level > player["等级"]){
          e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n你的等级不足\n[${thing}]需要${level}级才可装备`);
        }
        const buwei = equip["部位"];
        const player_equ0 = player_equ[buwei]["名称"];
        let word1= "";
        if(player_equ0 !== "" && player_equ0 !== undefined){
          await Add_bag(usr_qq, player_equ0["名称"], 1);
          word1 = `你卸下了[${player_equ0["名称"]}]，`
        }
        player_equ[buwei] = equip;
        await Write_equipment(usr_qq, player_equ);
        await Add_bag(usr_qq, thing, -1);
        e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n你` + word1 + `装备了[${thing}]`);
        let word = await my_equip(usr_qq);
        setTimeout(async function() {
              e.reply(word);
              }, 100);
        return;
    }

    async unequip(e) {
        e.cmd_msg = e.cmd_msg.replace("/", "");
        //有无存档
        let usr_qq = e.user_id;
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
          return;
        }
        if(await Read_state(usr_qq) == "组队战斗"){
          return;
        }
        let player = await Read_player(usr_qq);
        const thing = e.cmd_msg.replace("装备", "");
        let equip_list = await Read_equiplist(usr_qq);
        let equip = equip_list.find(obj => obj["名称"] == thing); 
        if(equip == undefined){
          e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n[${thing}]不存在于这方世界`);
          return;
        }
        const buwei = equip["部位"];
        let player_equ = Read_equipment(usr_qq);
        if(player_equ[buwei]["名称"] !== thing){
          e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n你没有装备[${thing}]`);
          return;
        }
        player_equ[buwei] = {"名称": ""};
        await Write_equipment(usr_qq, player_equ);
        await Add_bag(usr_qq, player_equ["名称"], 1);
        e.reply(`【${player.昵称} Lv.${player.等级}】\n————————————\n你卸下了[${player_equ["名称"]}]`);
        let word = await my_equip(usr_qq);
        setTimeout(async function() {
              e.reply(word);
              }, 100);
        return;
    }


    async myequip(e) {
        e.cmd_msg = e.cmd_msg.replace("/", "");
        //有无存档
        let usr_qq = e.user_id;
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
          return;
        }
        let word = await my_equip(usr_qq);
        e.reply(word);
        return;
    }






}
